# -*- coding:utf-8 -*-
# time: 2025/7/28 ♡  15:42
# author:张伟

from exts import db
from datetime import datetime
from sqlalchemy_serializer import SerializerMixin

class BoardModel(db.Model, SerializerMixin):
    serialize_only = ("id", "name", "priority", "create_time")
    __tablename__ = "board"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(20), unique=True)
    priority = db.Column(db.Integer, default=1)
    create_time = db.Column(db.DateTime, default=datetime.now)

    posts = db.relationship("PostModel", backref=db.backref("board", order_by="PostModel.create_time.desc()"),
                            cascade="all, delete-orphan")


class PostModel(db.Model, SerializerMixin):
    __tablename__ = "post"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(200), nullable=False)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)
    board_id = db.Column(db.Integer, db.ForeignKey("board.id"))
    author_id = db.Column(db.String(100), db.ForeignKey("user.id"))
    likes_num = db.Column(db.Integer, default=0)

    author = db.relationship("UserModel", backref=db.backref("posts"))

    # 在此处定义评论和加精的关联关系，显式声明级联删除，才能映射到数据库中进行级联删除
    comments = db.relationship("CommentModel", backref=db.backref('post', order_by="CommentModel.create_time.desc()"),
                               cascade="all, delete-orphan")
    like = db.relationship("LikeModel", backref="post", cascade="all, delete-orphan")


class BannerModel(db.Model, SerializerMixin):
    __tablename__ = 'banner'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), nullable=False)
    image_url = db.Column(db.String(255), nullable=False)
    link_url = db.Column(db.String(255), nullable=False)
    priority = db.Column(db.Integer, default=0)
    create_time = db.Column(db.DateTime, default=datetime.now)


class CommentModel(db.Model, SerializerMixin):
    serialize_only = ("id", "content", "create_time", "author.username", "post.id", "post.title")
    __tablename__ = 'comment'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)
    post_id = db.Column(db.Integer, db.ForeignKey("post.id"))
    author_id = db.Column(db.String(100), db.ForeignKey("user.id"), nullable=False)
    author = db.relationship("UserModel", backref='comments')




# 点赞
class LikeModel(db.Model, SerializerMixin):
    serialize_only = ("id", "post_id", "user_id", "like_status")
    __tablename__ = "likes"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    post_id = db.Column(db.Integer, db.ForeignKey("post.id", ondelete="CASCADE"))
    user_id = db.Column(db.String(100), db.ForeignKey("user.id", ondelete="CASCADE"))
    like_status = db.Column(db.Integer, default=0)